
class ListNode {
     int val;
     ListNode next;
     ListNode() {}
     ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

/**
 * 2. 两数相加
 * https://leetcode.cn/problems/add-two-numbers/description/
 */
public class Solution {
    //2、老师的
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode cur1 = l1, cur2 = l2;
        ListNode newHead = new ListNode(0);
        ListNode prev = newHead.next;//尾插操作的尾指针
        int t = 0;//进位

        while(cur1 != null || cur2 != null || t != 0) {
            //1、加上第一个链表
            if(cur1 != null) {
                t += cur1.val;
                cur1 = cur1.next;
            }
            //2、加上第二个链表
            if(cur2 != null) {
                t += cur2.val;
                cur2 = cur2.next;
            }

            prev.next = new ListNode(t % 10);
            prev = prev.next;
            t /= 10;
        }

        return newHead.next;
    }

    //自己写的版本
    public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
        int t = 0;
        ListNode head = new ListNode();
        ListNode cur = new ListNode();
        head.next = cur;

        while(l1 != null || l2 != null) {
            if(l1 != null && l2 != null)
                t += l1.val + l2.val;
            else if(l1 != null && l2 == null)
                t += l1.val;
            else
                t += l2.val;
            cur.val = t % 10;
            t /= 10;

            if(l1 != null) l1 = l1.next;
            if(l2 != null) l2 = l2.next;

            if(l1 != null || l2 != null) {
                cur.next = new ListNode();
                cur = cur.next;
            }
        }

        if(t == 1) {
            cur.next = new ListNode();
            cur.next.val = t;
        }

        return head.next;
    }
}